import subprocess, time, os, signal, sys, logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - SUPERVISOR - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler("pis_supervisor.log", encoding="utf-8"),
        logging.StreamHandler(),
    ],
)

logger = logging.getLogger("PIS-Supervisor")


def run_agent():
    """启动 main.py 子进程"""
    logger.info("启动 PIS-Agent 主进程...")
    process = subprocess.Popen([sys.executable, "main.py"])
    return process


def watch_agent():
    """守护循环"""
    proc = run_agent()
    last_mtime = os.path.getmtime("main.py")

    try:
        while True:
            time.sleep(3)

            # 检测 main.py 是否被修改
            new_mtime = os.path.getmtime("main.py")
            if new_mtime != last_mtime:
                logger.info("检测到 main.py 变更，准备重启进程。")
                proc.terminate()
                proc.wait(timeout=5)
                time.sleep(2)
                proc = run_agent()
                last_mtime = new_mtime
                continue

            # 检测主进程状态
            ret = proc.poll()
            if ret is not None:
                logger.warning(f"PIS-Agent 异常退出 (code={ret})，正在重启...")
                time.sleep(2)
                proc = run_agent()
                last_mtime = os.path.getmtime("main.py")

    except KeyboardInterrupt:
        logger.info("收到退出信号，关闭所有进程。")
        try:
            proc.terminate()
        except Exception:
            pass
        sys.exit(0)


if __name__ == "__main__":
    watch_agent()
